import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../resources/l10n/kq_intl.dart';
import '../../theme/kq_theme_manager.dart';
import '../bottomSheet/kq_botton_sheet_manger.dart';
import '../bottomSheet/sheets/kq_date_picker_bottom_sheet.dart';
import '../divider/kq_divider.dart';
import 'kq_date_widget.dart';
import 'kq_datetime_widget.dart';
import 'kq_time_widget.dart';

/// 日期时间范围选择器封装
/// 头部，提示，滚轮
class KqDateRangePicker extends StatefulWidget {

  /// 能滚动到的最小日期
  final DateTime? minDateTime;

  /// 能滚动到的最大日期
  final DateTime? maxDateTime;

  /// 初始选择的开始时间。默认当前时间
  final DateTime? initialStartDateTime;

  /// 初始选择的结束时间。默认当前时间
  final DateTime? initialEndDateTime;

  /// 日期时间显示的格式
  final String dateFormat;

  /// 滚轮显示的格式
  final String pickerFormat;

  /// 分钟间切换的差值
  final int minuteDivider;

  /// 是否正在选择结束时间
  final bool isSelectEndTime;

  /// 选择范围结果文字大小，默认16
  final double? resultFontSize;

  /// 提示文案
  final String? hintText;

  /// 左边按钮文字，默认“取消”
  final String? leftBtnText;

  /// 右边按钮文字，默认“确定”
  final String? rightBtnText;

  /// 时间选择组件显示的时间类型
  final KqDateTimePickerMode pickerMode;

  /// 自定义头部控件
  final List<Widget>? customHeaders;

  /// 时间选择组件的主题样式
  final KqPickerTitleConfig pickerTitleConfig;

  /// 点击【取消】回调给调用方的回调事件
  final Function()? onCancel;

  /// 时间滚动选择时候的回调事件
  final Function(DateTime dateTime)? onStartTimeChange;

  final Function(DateTime dateTime)? onEndTimeChange;

  final bool Function(DateTime startTime, DateTime endTime)? onConfirm;

  const KqDateRangePicker({Key? key,
    this.minDateTime,
    this.maxDateTime,
    this.initialStartDateTime,
    this.initialEndDateTime,
    this.customHeaders,
    this.hintText,
    this.resultFontSize,
    this.isSelectEndTime = false,
    required this.pickerFormat,
    required this.dateFormat,
    this.minuteDivider = 1,
    this.leftBtnText,
    this.rightBtnText,
    this.onCancel,
    this.onStartTimeChange,
    this.onEndTimeChange,
    this.onConfirm,
    this.pickerMode = KqDateTimePickerMode.date,
    this.pickerTitleConfig = KqPickerTitleConfig.Default}) : super(key: key);

  @override
  KqDateRangePickerState createState() => KqDateRangePickerState();
}

class KqDateRangePickerState extends State<KqDateRangePicker> {

  bool isSelectEndTime = false;

  DateTime? startDateTime;
  DateTime? endDateTime;

  @override
  void initState() {
    super.initState();
    isSelectEndTime = widget.isSelectEndTime;
    startDateTime = widget.initialStartDateTime;
    endDateTime = widget.initialEndDateTime;
  }

  @override
  Widget build(BuildContext context) {
    var pickerStart = createStartPicker();
    var pickerEnd = createEndPicker();

    return UnconstrainedBox(
        child: SizedBox(
            width: context.width,
            child: Material(
                shape: const RoundedRectangleBorder(),
                color:
                KqThemeManager.instance
                    .getConfig()
                    .dialogConfig
                    .bgColor ??
                    KqThemeColors.bgWhite,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Visibility(
                      visible: isSelectEndTime,
                      child: pickerEnd!,
                    ),
                    Visibility(
                      visible: !isSelectEndTime,
                      child: pickerStart!,
                    )
                  ],
                ))));
  }

  List<Widget> createChildren() {
    var startTimeString = DateFormat(widget.dateFormat).format(startDateTime!);
    var endTimeString = DateFormat(widget.dateFormat).format(endDateTime!);

    List<Widget> children = [];

    children.add(SizedBox(
      height: widget.customHeaders == null ? 10.r : 16.r,
    ));

    if (widget.customHeaders != null) {
      children.addAll(widget.customHeaders!);
      children.add(Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(
            width: 16.r,
          ),
          Text(
            KqIntl.currentResource.timeRange,
            style: TextStyle(fontSize: 12.sp, color: KqThemeColors.text8C),
          )
        ],
      ));
    }

    children.add(Padding(
      padding: EdgeInsets.only(top: 20.r, bottom: 6.r),
      child: Row(
        children: [
          SizedBox(
            width: 20.r,
          ),
          Expanded(
              child: KqInkWell(
                onTap: () {
                  setState(() {
                    isSelectEndTime = false;
                  });
                },
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      startTimeString,
                      style: TextStyle(
                          fontSize: widget.resultFontSize ?? 16.sp,
                          color: !isSelectEndTime
                              ? KqThemeManager
                              .getCommonConfig()
                              .mainLightColor!
                              : KqThemeColors.text26),
                    ),
                    SizedBox(
                      height: 6.r,
                    ),
                    KqDivider(
                      height: 2.r,
                      color: !isSelectEndTime
                          ? KqThemeManager
                          .getCommonConfig()
                          .mainLightColor!
                          : KqThemeColors.text8C,
                    )
                  ],
                ),
              )),
          SizedBox(
            width: 16.r,
          ),
          Text(
            KqIntl.currentResource.to,
            style: TextStyle(
                fontSize: 16.sp,
                color: KqThemeColors.text222,
                fontWeight: FontWeight.w600),
          ),
          SizedBox(
            width: 16.r,
          ),
          Expanded(
              child: KqInkWell(
                onTap: () {
                  setState(() {
                    isSelectEndTime = true;
                  });
                },
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      endTimeString,
                      style: TextStyle(
                          fontSize: widget.resultFontSize ?? 16.sp,
                          color: isSelectEndTime
                              ? KqThemeManager
                              .getCommonConfig()
                              .mainLightColor!
                              : KqThemeColors.text26),
                    ),
                    SizedBox(
                      height: 6.r,
                    ),
                    KqDivider(
                      height: 2.r,
                      color: isSelectEndTime
                          ? KqThemeManager
                          .getCommonConfig()
                          .mainLightColor!
                          : KqThemeColors.text8C,
                    )
                  ],
                ),
              )),
          SizedBox(
            width: 20.r,
          )
        ],
      ),
    ));

    if (widget.hintText != null) {
      children.add(Row(
        children: [
          Expanded(
              child: Text(
                widget.hintText!,
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 12.sp, color: const Color(0xffFF9F0A)),
              ))
        ],
      ));
    }
    return children;
  }

  Widget? createStartPicker() {
    var children = createChildren();
    switch (widget.pickerMode) {
      case KqDateTimePickerMode.date:
        return KqDateWidget(
          minDateTime: widget.minDateTime,
          maxDateTime: widget.maxDateTime,
          customHeaders: children,
          initialDateTime: startDateTime,
          dateFormat: widget.pickerFormat,
          leftBtnText: widget.leftBtnText,
          rightBtnText: widget.rightBtnText,
          pickerTitleConfig: widget.pickerTitleConfig,
          onCancel: widget.onCancel,
          canPop: false,
          onChange: (dateTime, selectedIndex) {
            setState(() {
              startDateTime = dateTime;
              widget.onStartTimeChange?.call(dateTime);
            });
          },
          onConfirm: (dateTime, selectedIndex) {
            startDateTime = dateTime;
            var shouldPop = widget.onConfirm!.call(startDateTime!, endDateTime!);
            if (shouldPop) {
              Navigator.pop(context);
            }
            return false;
          },
          showBottomButton: false,
        );
      case KqDateTimePickerMode.time:
        return KqTimeWidget(
          minDateTime: widget.minDateTime,
          maxDateTime: widget.maxDateTime,
          customHeaders: children,
          canPop: false,
          leftBtnText: widget.leftBtnText,
          rightBtnText: widget.rightBtnText,
          initDateTime: startDateTime,
          dateFormat: widget.pickerFormat,
          minuteDivider: widget.minuteDivider,
          pickerTitleConfig: widget.pickerTitleConfig,
          onCancel: widget.onCancel,
          onChange: (dateTime, selectedIndex) {
            setState(() {
              startDateTime = dateTime;
              widget.onStartTimeChange?.call(dateTime);
            });
          },
          onConfirm: (dateTime, selectedIndex) {
            startDateTime = dateTime;
            var shouldPop = widget.onConfirm!.call(startDateTime!, endDateTime!);
            if (shouldPop) {
              Navigator.pop(context);
            }
            return false;
          },
          showBottomButton: false,
        );
      case KqDateTimePickerMode.datetime:
        return KqDateTimeWidget(
          minDateTime: widget.minDateTime,
          maxDateTime: widget.maxDateTime,
          customHeaders: children,
          canPop: false,
          leftBtnText: widget.leftBtnText,
          rightBtnText: widget.rightBtnText,
          initDateTime: startDateTime,
          dateFormat: widget.pickerFormat,
          minuteDivider: widget.minuteDivider,
          pickerTitleConfig: widget.pickerTitleConfig,
          onCancel: widget.onCancel,
          onChange: (dateTime, selectedIndex) {
            setState(() {
              startDateTime = dateTime;
              widget.onStartTimeChange?.call(dateTime);
            });
          },
          onConfirm: (dateTime, selectedIndex) {
            startDateTime = dateTime;
            var shouldPop = widget.onConfirm!.call(startDateTime!, endDateTime!);
            if (shouldPop) {
              Navigator.pop(context);
            }
            return false;
          },
          showBottomButton: false,
        );
    }
  }

  Widget? createEndPicker() {
    var children = createChildren();
    switch (widget.pickerMode) {
      case KqDateTimePickerMode.date:
        return KqDateWidget(
          minDateTime: widget.minDateTime,
          maxDateTime: widget.maxDateTime,
          customHeaders: children,
          initialDateTime: endDateTime,
          dateFormat: widget.pickerFormat,
          pickerTitleConfig: widget.pickerTitleConfig,
          onCancel: widget.onCancel,
          leftBtnText: widget.leftBtnText,
          rightBtnText: widget.rightBtnText,
          canPop: false,
          onChange: (dateTime, selectedIndex) {
            setState(() {
              endDateTime = dateTime;
              widget.onEndTimeChange?.call(dateTime);
            });
          },
          onConfirm: (dateTime, selectedIndex) {
            endDateTime = dateTime;
            var shouldPop = widget.onConfirm!.call(startDateTime!, endDateTime!);
            if (shouldPop) {
              Navigator.pop(context);
            }
            return false;
          },
          showBottomButton: false,
        );
      case KqDateTimePickerMode.time:
        return KqTimeWidget(
          minDateTime: widget.minDateTime,
          maxDateTime: widget.maxDateTime,
          customHeaders: children,
          initDateTime: endDateTime,
          dateFormat: widget.pickerFormat,
          minuteDivider: widget.minuteDivider,
          pickerTitleConfig: widget.pickerTitleConfig,
          onCancel: widget.onCancel,
          leftBtnText: widget.leftBtnText,
          rightBtnText: widget.rightBtnText,
          canPop: false,
          onChange: (dateTime, selectedIndex) {
            setState(() {
              endDateTime = dateTime;
              widget.onEndTimeChange?.call(dateTime);
            });
          },
          onConfirm: (dateTime, selectedIndex) {
            endDateTime = dateTime;
            var shouldPop = widget.onConfirm!.call(startDateTime!, endDateTime!);
            if (shouldPop) {
              Navigator.pop(context);
            }
            return false;
          },
          showBottomButton: false,
        );
      case KqDateTimePickerMode.datetime:
        return KqDateTimeWidget(
          minDateTime: widget.minDateTime,
          maxDateTime: widget.maxDateTime,
          customHeaders: children,
          initDateTime: endDateTime,
          dateFormat: widget.pickerFormat,
          minuteDivider: widget.minuteDivider,
          pickerTitleConfig: widget.pickerTitleConfig,
          onCancel: widget.onCancel,
          leftBtnText: widget.leftBtnText,
          rightBtnText: widget.rightBtnText,
          canPop: false,
          onChange: (dateTime, selectedIndex) {
            setState(() {
              endDateTime = dateTime;
              widget.onEndTimeChange?.call(dateTime);
            });
          },
          onConfirm: (dateTime, selectedIndex) {
            endDateTime = dateTime;
            var shouldPop = widget.onConfirm!.call(startDateTime!, endDateTime!);
            if (shouldPop) {
              Navigator.pop(context);
            }
            return false;
          },
          showBottomButton: false,
        );
    }
  }

}
